import {
  _decorator,
  Component,
  director,
  Node,
  Prefab,
  Sprite,
  tween,
  UITransform,
  Vec3,
} from "cc";
import { layerAction1 } from "./layerAction1";
import { layerAction2 } from "./layerAction2";
import { layerAction3 } from "./layerAction3";
import { gameConfig } from "./data/gameConfig";
import { perBlock } from "./prepab/perBlock";
import { mainView } from "./mainView";
import { loadPool } from "./res/loadPool";
import { bgmName, emits } from "./data/enmus";
import { audioTool } from "./untils/audioTool";
import { wxAd } from "./AD/wxAd";
import { adMgr } from "./AD/adMgr";
import { adConfig } from "./AD/adConfig";
const { ccclass, property } = _decorator;

@ccclass("layerRootAction")
export class layerRootAction extends Component {
  layerAction1: layerAction1 = null;
  @property(layerAction2) layerAction2: layerAction2 = null;
  @property(layerAction3) layerAction3: layerAction3 = null;

  start() {
    director.on(emits.isFuhuo, this.isFuhuo, this);
    this.loadLayerAction1();
  }
  protected onDestroy(): void {
    this.unscheduleAllCallbacks();
  }
  // 解决layerAction1循环调用警告
  private loadLayerAction1() {
    if (!this.layerAction1) {
      this.layerAction1 = this.node
        .getChildByName("layer1")
        .getComponent(layerAction1);
    }
  }
  // 开始游戏
  startGame() {
    this.loadLayerAction1();
    this.layerAction1.delAll();
    this.layerAction2.delAll();
    this.layerAction3.delAll();
    //传入当前关卡并开始游戏
    this.layerAction1.startGame(gameConfig.nowLevel);
  }

  // 在layer1中克隆并移动元素
  oneToThree(item: perBlock, perBlock: Prefab) {
    let cloneItem = item.cloneItem(this.node, perBlock);
    this.layerAction1.showShadow();
    let slotPos = this.layerAction3.getSlotPos(cloneItem);
    let localPos = this.node
      .getComponent(UITransform)
      .convertToNodeSpaceAR(slotPos);
    tween(cloneItem.node)
      .to(0.15, { position: localPos })
      .call(() => {
        this.layerAction3.add(cloneItem);
        // 是否消除
        let isDelet = this.layerAction3.delItem();
        if (isDelet) {
          if (
            this.layerAction1.getItemSize() == 0 &&
            this.layerAction2.getItemSize() == 0 &&
            this.layerAction3.getItemSize() == 0
          ) {
            console.log("游戏胜利");
            audioTool.ins.playSound(bgmName.sound_win);
            this.node.parent.getComponent(mainView).nextLevel();
          }
        }
        this.checkGameOver();
      })
      .start();
  }
  // 在layer2中移动元素
  twoToThree(item: perBlock) {
    item.node.parent = this.node;
    item.node.setPosition(
      this.node
        .getComponent(UITransform)
        .convertToNodeSpaceAR(item.getTempPos())
    );
    let slotPos = this.layerAction3.getSlotPos(item);
    let localPos = this.node
      .getComponent(UITransform)
      .convertToNodeSpaceAR(slotPos);
    tween(item.node)
      .to(0.15, { position: localPos })
      .call(() => {
        this.layerAction3.add(item);
        // 是否消除
        let isDelet = this.layerAction3.delItem();
        if (isDelet) {
          if (
            this.layerAction1.getItemSize() == 0 &&
            this.layerAction2.getItemSize() == 0 &&
            this.layerAction3.getItemSize() == 0
          ) {
            // 游戏胜利
            console.log("游戏胜利");
            audioTool.ins.playSound(bgmName.sound_win);
            this.node.parent.getComponent(mainView).nextLevel();
          }
        }
      })
      .start();
    this.checkGameOver();
  }
  // 判断游戏是否结束
  checkGameOver() {
    if (this.layerAction3.getItemSize() >= 7) {
      console.log("游戏失败");
      audioTool.ins.playSound(bgmName.sound_shibai);
      audioTool.ins.stopMusic();
      if (gameConfig.fuhouNum > 0) {
        loadPool.ins.getPoolNode("gameOver1", gameConfig.gameRoot);
      } else {
        loadPool.ins.getPoolNode("gameOver2", gameConfig.gameRoot);
      }
    }
  }
  /**
   * 功能按钮
   */
  // 复活
  isFuhuo() {
    this.yichu();
    audioTool.ins.playMusic(bgmName.game_bg);
  }
  // 设置
  settingBtn() {
    audioTool.ins.playSound(bgmName.sound_btn);
    loadPool.ins.getPoolNode("setting", gameConfig.gameRoot);
    director.emit(emits.backIsShow, 1);
  }
  /**
   * 移出三个棋子
   * @returns
   */
  yichuBtn() {
    if (gameConfig.yichuNum < 1) {
      loadPool.ins.getPoolNode("tips", gameConfig.gameRoot);
      director.emit(emits.tipMsg, "The number of attempts has been exhausted");
      return;
    }
    if (this.layerAction3.getItemSize() == 0) {
      loadPool.ins.getPoolNode("tips", gameConfig.gameRoot);
      director.emit(emits.tipMsg, "No need to use props");
      return;
    }
    if (adConfig.isShowAd) {
      // 显示视频广告
      adMgr.showVideo(() => {
        // audioTool.ins.stopMusic()
        this.yichu();
        // 使用一次机会，图标变灰色
        gameConfig.yichuNum -= 1;
        director.emit(emits.daojuStatus);
        // audioTool.ins.playMusic(bgmName.game_bg)
      });
    } else {
      this.yichu();
      // 使用一次机会，图标变灰色
      gameConfig.yichuNum -= 1;
      director.emit(emits.daojuStatus);
    }
  }
  private yichu() {
    let removeItem = this.layerAction3.getRemoveItem();
    if (removeItem.length == 0) {
      console.log("需要移出的列表为0");
      return;
    }
    this.layerAction3.restOrder();
    let local = this.node
      .getComponent(UITransform)
      .convertToNodeSpaceAR(this.layerAction2.getWorldPos());
    for (let item of removeItem) {
      item.node.setParent(this.node);
      item.node.setPosition(
        this.node
          .getComponent(UITransform)
          .convertToNodeSpaceAR(item.getTempPos())
      );
      tween(item.node)
        .to(0.1, { position: local })
        .call(() => {
          this.layerAction2.addItem(item);
        })
        .start();
    }
  }
  /**
   * 撤回一个棋子
   * @returns
   */
  chehuiBtn() {
    if (gameConfig.chehuiNum < 1) {
      loadPool.ins.getPoolNode("tips", gameConfig.gameRoot);
      director.emit(emits.tipMsg, "The number of attempts has been exhausted");
      return;
    }
    if (this.layerAction3.getItemSize() == 0) {
      loadPool.ins.getPoolNode("tips", gameConfig.gameRoot);
      director.emit(emits.tipMsg, "No need to use any props");
      return;
    }
    // 如果开启广告需转发撤回，否则直接撤回
    if (adConfig.isShowAd) {
      // audioTool.ins.stopMusic()
      if (adConfig.isShowAd) {
        // 显示视频广告
        adMgr.showVideo(() => {
          // audioTool.ins.stopMusic()
          this.chehui();
          // 使用一次机会，图标变灰色
          gameConfig.yichuNum -= 1;
          director.emit(emits.daojuStatus);
          // audioTool.ins.playMusic(bgmName.game_bg)
        });
      }
    } else {
      this.chehui();
    }
  }
  chehui() {
    let endItem = this.layerAction3.getEndItem();
    if (!endItem) {
      return;
    }
    endItem.node.parent = this.node;
    endItem.node.setPosition(
      this.node
        .getComponent(UITransform)
        .convertToNodeSpaceAR(endItem.getTempPos())
    );
    let targetPos = this.node
      .getComponent(UITransform)
      .convertToNodeSpaceAR(endItem.original.node.getWorldPosition());
    tween(endItem.node)
      .to(0.12, { position: targetPos })
      .call(() => {
        endItem.original.node.active = true;
        this.layerAction1.showShadow();
      })
      .removeSelf()
      .start();
    this.layerAction3.restOrder();
    // 使用一次机会，图标变灰色
    gameConfig.chehuiNum -= 1;
    director.emit(emits.daojuStatus);
    // 撤回提示
    loadPool.ins.getPoolNode("tips", this.node);
    director.emit(emits.tipMsg, "​​Undo Successful​​");
  }
  /**
   * 打乱顺序
   * @returns
   */
  randomBtn() {
    if (gameConfig.randomNum < 1) {
      loadPool.ins.getPoolNode("tips", gameConfig.gameRoot);
      director.emit(emits.tipMsg, "The number of attempts has been exhausted");
      return;
    }
    if (adConfig.isShowAd) {
      adMgr.showVideo(() => {
        // audioTool.ins.stopMusic()
        this.layerAction1.randomItem();
        // 使用一次机会，图标变灰色
        gameConfig.randomNum -= 1;
        director.emit(emits.daojuStatus);
        // audioTool.ins.playMusic(bgmName.game_bg)
      });
    } else {
      audioTool.ins.stopMusic();
      this.layerAction1.randomItem();
      // 使用一次机会，图标变灰色
      gameConfig.randomNum -= 1;
      director.emit(emits.daojuStatus);
      audioTool.ins.playMusic(bgmName.game_bg);
    }
  }
  // 获取layer3的元素数量
  getLayer3Size() {
    return this.layerAction3.getItemSize();
  }
  protected onDisable(): void {
    this.unscheduleAllCallbacks();
  }
}
